package com.gl.saasservice.device.service;

import com.alibaba.fastjson.JSON;
import com.gl.common.util.Base64Utils;
import com.gl.common.util.SecurityUtils;
import com.gl.common.vo.ApiData;
import com.gl.framework.security.LoginUser;
import com.gl.framework.web.response.Result;
import com.gl.portal.system.entity.SysUser;
import com.gl.portal.system.repository.SysUserRepository;
import com.gl.portal.system.vo.SysUserVo;
import com.gl.saasservice.device.entity.Device;
import com.gl.saasservice.device.repository.DeviceRepository;
import com.gl.saasservice.device.vo.DeviceVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class DeviceService {
    private static final Logger log = LoggerFactory.getLogger(DeviceService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private DeviceRepository deviceRepository;

    public Result deviceList(String token, Integer pageNumber, Integer pageSize) {
        log.info("DeviceService deviceList, token={}", token);
        try {
            ApiData<DeviceVO> apiData = new ApiData<>();

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            where.append(" where 1 = 1 and d.del_status = 0");

            String count = "SELECT COUNT(1) FROM saas_device d";
            Long total = jdbcTemplate.queryForObject(count + where, Long.class, args.toArray());
            if (total == 0) {
                return Result.success(apiData);
            }

            // 查询分页数据
            String sql = "SELECT * FROM saas_device d";
            String offsets = " limit ? offset ?";
            where.append(" ORDER BY d.operator_time desc").append(offsets);
            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<DeviceVO> data = jdbcTemplate.query(sql + where, new BeanPropertyRowMapper<>(DeviceVO.class), args.toArray());

            //查询操作人姓名
            List<Long> operatorIds = data.stream().map(DeviceVO::getOperatorId).distinct().collect(Collectors.toList());
            if (!operatorIds.isEmpty()) {
                Map<Long, String> map = sysUserRepository.findByIdIn(operatorIds).stream().collect(Collectors.toMap(SysUser::getId, SysUser::getUserName));
                if (!map.isEmpty()) {
                    data.forEach(vo -> vo.setOperatorName(map.get(vo.getOperatorId())));
                }
            }

            apiData.setTotal(total);
            apiData.setData(data);
            return Result.success(apiData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.fail();
        }
    }

    public Result saveOrUpdate(String token, DeviceVO vo) {
        log.info("DeviceService saveOrUpdate, vo={}", JSON.toJSONString(vo));
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUserVo user = loginUser.getUser();
            Date date = new Date();

            if (vo.getId() == null) {//新增
                List<Device> devices = deviceRepository.findByNumberAndDelStatus(vo.getNumber(), 0);
                if (!devices.isEmpty()) {
                    return Result.fail("该设备编号已存在，不可重复添加");
                }
                Device device = new Device();
                device.setNumber(vo.getNumber());
                device.setModel(vo.getModel());
                device.setStatus(1);
                device.setDelStatus(0);
                device.setOperatorId(user.getId());
                device.setOperatorTime(date);
                device.setLastUpdateTime(date);
                deviceRepository.save(device);
            } else {//编辑
                Optional<Device> deviceOptional = deviceRepository.findById(vo.getId());
                if (!deviceOptional.isPresent()) {
                    return Result.fail("设备不存在");
                }
                Device device = deviceOptional.get();

                if (!vo.getNumber().equals(device.getNumber())) {
                    List<Device> devices = deviceRepository.findByNumberAndDelStatus(vo.getNumber(), 0);
                    if (!devices.isEmpty()) {
                        return Result.fail("该设备编号已存在，不可重复添加");
                    }
                }
                device.setNumber(vo.getNumber());
                device.setModel(vo.getModel());
                device.setLastUpdateTime(date);
                deviceRepository.save(device);
            }

            return Result.success(null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.fail();
        }
    }

    public Result delete(String token, DeviceVO vo) {
        log.info("DeviceService delete, vo={}", JSON.toJSONString(vo));
        try {
            if (vo.getId() == null) {
                return Result.fail("id为空");
            }

            Optional<Device> deviceOptional = deviceRepository.findById(vo.getId());
            if (!deviceOptional.isPresent()) {
                return Result.fail("设备不存在");
            }
            Device device = deviceOptional.get();
            device.setDelStatus(1);
            deviceRepository.save(device);

            return Result.success(null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.fail();
        }
    }

    public Result setPwd(String token, DeviceVO vo) {
        log.info("DeviceService setPwd, vo={}", JSON.toJSONString(vo));
        try {
            if (vo.getId() == null) {
                return Result.fail("id为空");
            }
            if (StringUtils.isBlank(vo.getPwd())) {
                return Result.fail("密码为空");
            }

            Optional<Device> deviceOptional = deviceRepository.findById(vo.getId());
            if (!deviceOptional.isPresent()) {
                return Result.fail("设备不存在");
            }
            Device device = deviceOptional.get();

            String pwd = Base64Utils.encode(vo.getPwd().getBytes());
            device.setPwd(pwd);
            device.setLastUpdateTime(new Date());
            deviceRepository.save(device);

            return Result.success(null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.fail();
        }
    }


}
